package com.hxx.widget.richtext.editor

import java.util.*

/**
 * 历史数据保存
 */
class BaseEditorSaveStater private constructor() : EditorSaveStater {

    private var stateListener: EditorSaveStater.OnStateChangedListener? = null
    private val historyStack = Stack<EditorHistory>()
    private val redoStack = Stack<EditorHistory>()

    /**
     * 是否能够后退了，当历史栈为空或者是数量为1时候不能后退
     */
    override fun canUndo(): Boolean {
        return !historyStack.empty()
    }

    /**
     * 是否能前进，当 @redoStack 为空的时候则不能够前进
     */
    override fun canRedo(): Boolean {
        return !redoStack.empty()
    }

    /**
     * 保存当前状态 清空前进数据栈，保存当前信息到历史栈
     */
    override fun saveNode(editorHistory: EditorHistory) {
        redoStack.clear()
        historyStack.push(editorHistory)
        stateListener?.onChanged()
    }

    /**
     * 获取前进栈的数据信息
     */
    override fun redoNode(): EditorHistory {
        redoStack.pop().apply {
            historyStack.push(this)
        }
        stateListener?.onChanged()
        return historyStack.peek()
    }

    /**
     * 获取后退栈的数据信息
     */
    override fun undoNode(): EditorHistory {
        historyStack.pop().apply {
            redoStack.push(this)
        }
        stateListener?.onChanged()
        return redoStack.peek()
    }

    override fun setStateChangedListener(listener: EditorSaveStater.OnStateChangedListener) {
        this.stateListener = listener
        stateListener?.onChanged()
    }


    companion object{
        fun instance():BaseEditorSaveStater{
            return BaseEditorSaveStater()
        }
    }
}